<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="药品名称">
          <el-input v-model="searchForm.drugName" placeholder="请输入药品名称" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="药品编码">
          <el-input v-model="searchForm.drugCode" placeholder="请输入药品编码" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="searchForm.batchNumber" placeholder="请输入批次号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select v-model="searchForm.inventoryStatus" placeholder="请选择库存状态" clearable>
            <el-option label="正常" value="normal" />
            <el-option label="低库存" value="low" />
            <el-option label="已过期" value="expired" />
            <el-option label="即将过期" value="nearExpiry" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>药品库存</h3>
          <div>
            <el-button 
              type="primary" 
              @click="handleAddInventory" 
              v-permission="'drug_inventory:create'"
            >
              添加库存
            </el-button>
            <el-button 
              type="warning" 
              @click="handleExpiringDrugs" 
              v-permission="'drug_inventory:read'"
            >
              效期预警
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="inventoryList"
        border
        style="width: 100%"
        row-key="id"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="drugInfo.drugCode" label="药品编码" min-width="120" />
        <el-table-column prop="drugInfo.name" label="药品名称" min-width="150" />
        <el-table-column prop="drugInfo.specification" label="规格" min-width="120" />
        <el-table-column prop="batchNumber" label="批次号" min-width="120" />
        <el-table-column prop="quantity" label="库存数量" min-width="100">
          <template #default="scope">
            <el-tag :type="getInventoryStatusType(scope.row)" effect="plain">
              {{ scope.row.quantity }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="有效期至" min-width="120" sortable="custom">
          <template #default="scope">
            <span :class="isNearExpiry(scope.row.expirationDate) ? 'warning-text' : ''">
              {{ scope.row.expirationDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="drugInfo.manufacturer" label="生产厂家" min-width="180" show-overflow-tooltip />
        <el-table-column prop="purchasePrice" label="采购单价" min-width="100">
          <template #default="scope">
            {{ formatCurrency(scope.row.purchasePrice) }}
          </template>
        </el-table-column>
        <el-table-column prop="receiveDate" label="采购日期" min-width="120" sortable="custom" />
        <el-table-column label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row)">
              {{ getStatusLabel(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleViewDetail(scope.row)"
              v-permission="'drug_inventory:read'"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleUpdateInventory(scope.row)"
              v-permission="'drug_inventory:update'"
            >
              调整
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDiscard(scope.row)"
              v-if="!scope.row.isExpired"
              v-permission="'drug_inventory:update'"
            >
              报废
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="limit"
          @size-change="fetchInventory"
          @current-change="fetchInventory"
        />
      </div>
    </el-card>

    <!-- 库存调整对话框 -->
    <el-dialog
      title="库存调整"
      v-model="inventoryDialog.visible"
      width="500px"
    >
      <el-form :model="inventoryDialog.form" label-width="120px" ref="inventoryFormRef">
        <el-form-item label="药品名称">
          <el-input v-model="inventoryDialog.form.drugName" disabled />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="inventoryDialog.form.batchNumber" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="inventoryDialog.form.currentQuantity" disabled>
            <template #append>{{ inventoryDialog.form.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="调整数量" prop="adjustQuantity">
          <el-input-number 
            v-model="inventoryDialog.form.adjustQuantity" 
            :min="-inventoryDialog.form.currentQuantity" 
            :max="1000"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因" prop="reason">
          <el-select v-model="inventoryDialog.form.reason" placeholder="请选择调整原因" style="width: 100%">
            <el-option label="盘盈" value="surplus" />
            <el-option label="盘亏" value="loss" />
            <el-option label="损耗" value="damage" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="inventoryDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="inventoryDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmInventoryAdjust" :loading="inventoryDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报废对话框 -->
    <el-dialog
      title="药品报废"
      v-model="discardDialog.visible"
      width="500px"
    >
      <el-form :model="discardDialog.form" label-width="120px" ref="discardFormRef">
        <el-form-item label="药品名称">
          <el-input v-model="discardDialog.form.drugName" disabled />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="discardDialog.form.batchNumber" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="discardDialog.form.currentQuantity" disabled>
            <template #append>{{ discardDialog.form.unit }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="报废数量" prop="discardQuantity">
          <el-input-number 
            v-model="discardDialog.form.discardQuantity" 
            :min="1" 
            :max="discardDialog.form.currentQuantity"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报废原因" prop="reason">
          <el-select v-model="discardDialog.form.reason" placeholder="请选择报废原因" style="width: 100%">
            <el-option label="过期" value="expired" />
            <el-option label="质量问题" value="quality" />
            <el-option label="包装破损" value="damaged" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="discardDialog.form.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="discardDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmDiscard" :loading="discardDialog.loading">
            确认报废
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { drugInventoryAPI } from '@/utils/api'
import { formatCurrency } from '@/utils/format'

const router = useRouter()

// 数据列表
const inventoryList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(20)
const sortBy = ref('expiryDate')
const order = ref('asc')

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  drugName: '',
  drugCode: '',
  batchNumber: '',
  inventoryStatus: ''
})

// 库存调整对话框
const inventoryDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: '',
    drugName: '',
    batchNumber: '',
    currentQuantity: 0,
    adjustQuantity: 0,
    unit: '',
    reason: '',
    remark: ''
  }
})

// 报废对话框
const discardDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: '',
    drugName: '',
    batchNumber: '',
    currentQuantity: 0,
    discardQuantity: 0,
    unit: '',
    reason: '',
    remark: ''
  }
})

// 获取库存列表
const fetchInventory = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      sortBy: sortBy.value,
      order: order.value,
      ...searchForm
    }
    
    const res = await drugInventoryAPI.getInventories(params)
    if (res.success && res.data) {
      inventoryList.value = res.data.inventory || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取库存列表失败')
    }
  } catch (error) {
    console.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchInventory()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  page.value = 1
  fetchInventory()
}

// 排序变化
const handleSortChange = (column) => {
  if (column.prop) {
    sortBy.value = column.prop
    order.value = column.order === 'ascending' ? 'asc' : 'desc'
    fetchInventory()
  }
}

// 添加库存
const handleAddInventory = () => {
  router.push('/drugs/inventory/add')
}

// 查看即将过期的药品
const handleExpiringDrugs = () => {
  router.push('/drugs/inventory/expiring')
}

// 查看库存详情
const handleViewDetail = (row) => {
  router.push(`/drugs/inventory/detail/${row.id}`)
}

// 调整库存
const handleUpdateInventory = (row) => {
  inventoryDialog.form.id = row.id
  inventoryDialog.form.drugName = row.drugInfo.name
  inventoryDialog.form.batchNumber = row.batchNumber
  inventoryDialog.form.currentQuantity = row.quantity
  inventoryDialog.form.adjustQuantity = 0
  inventoryDialog.form.unit = ''
  inventoryDialog.form.reason = ''
  inventoryDialog.form.remark = ''
  inventoryDialog.visible = true
}

// 确认库存调整
const confirmInventoryAdjust = async () => {
  if (!inventoryDialog.form.reason) {
    ElMessage.warning('请选择调整原因')
    return
  }

  inventoryDialog.loading = true
  try {
    const res = await drugInventoryAPI.updateInventory(inventoryDialog.form.id, {
      adjustQuantity: inventoryDialog.form.adjustQuantity,
      reason: inventoryDialog.form.reason,
      remark: inventoryDialog.form.remark
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('库存调整成功')
      inventoryDialog.visible = false
      fetchInventory()
    } else {
      ElMessage.error(res.data.message || '库存调整失败')
    }
  } catch (error) {
    console.error('库存调整失败', error)
    ElMessage.error('库存调整失败')
  } finally {
    inventoryDialog.loading = false
  }
}

// 药品报废
const handleDiscard = (row) => {
  discardDialog.form.id = row.id
  discardDialog.form.drugName = row.drugInfo.name
  discardDialog.form.batchNumber = row.batchNumber
  discardDialog.form.currentQuantity = row.quantity
  discardDialog.form.discardQuantity = row.quantity
  discardDialog.form.unit = ''
  discardDialog.form.reason = ''
  discardDialog.form.remark = ''
  discardDialog.visible = true
}

// 确认报废
const confirmDiscard = async () => {
  if (!discardDialog.form.reason) {
    ElMessage.warning('请选择报废原因')
    return
  }

  discardDialog.loading = true
  try {
    const res = await drugInventoryAPI.updateInventory(discardDialog.form.id, {
      adjustQuantity: -discardDialog.form.discardQuantity,
      reason: 'discard',
      discardReason: discardDialog.form.reason,
      remark: discardDialog.form.remark
    })
    
    if (res.data && res.data.success) {
      ElMessage.success('药品报废成功')
      discardDialog.visible = false
      fetchInventory()
    } else {
      ElMessage.error(res.data.message || '药品报废失败')
    }
  } catch (error) {
    console.error('药品报废失败', error)
    ElMessage.error('药品报废失败')
  } finally {
    discardDialog.loading = false
  }
}

// 判断药品是否即将过期（距离过期不到30天）
const isNearExpiry = (expiryDate) => {
  if (!expiryDate) return false
  
  const today = new Date()
  const expiry = new Date(expiryDate)
  const diffTime = expiry - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  return diffDays > 0 && diffDays <= 30
}

// 获取库存状态类型
const getInventoryStatusType = (row) => {
  if (!row) return 'info'
  
  if (row.quantity <= 0) {
    return 'danger'
  }
  
  // 如果不存在预警值，默认设为10
  const minInventory = row.minInventory || 10
  
  if (row.quantity <= minInventory) {
    return 'warning'
  }
  
  return 'success'
}

// 获取状态标签类型
const getStatusTagType = (row) => {
  if (isExpired(row.expirationDate)) {
    return 'danger'
  }
  
  if (isNearExpiry(row.expirationDate)) {
    return 'warning'
  }
  
  if (row.quantity <= (row.minInventory || 10)) {
    return 'warning'
  }
  
  return 'success'
}

// 判断药品是否已过期
const isExpired = (expiryDate) => {
  if (!expiryDate) return false
  
  const today = new Date()
  const expiry = new Date(expiryDate)
  
  return expiry < today
}

// 获取状态标签文本
const getStatusLabel = (row) => {
  if (isExpired(row.expirationDate)) {
    return '已过期'
  }
  
  if (isNearExpiry(row.expirationDate)) {
    return '即将过期'
  }
  
  if (row.quantity <= 0) {
    return '无库存'
  }
  
  if (row.quantity <= (row.minInventory || 10)) {
    return '低库存'
  }
  
  return '正常'
}

// 生命周期钩子
onMounted(() => {
  fetchInventory()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.warning-text {
  color: #E6A23C;
}
</style>